/*
 * This file is part of ddesktop: remote desktop system for iPad 
 *
 * Copyright (C) 2010 Kazuhiro Satoh
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. if not, see <http://www.gnu.org/licenses/>.
 */

#import "KeyboardView.h"
#import "constants.h"


@implementation KeyboardView


@synthesize delegate = _delegate;
@synthesize keyboardSize = _keyboardSize;
@synthesize keyboardIsHidden = _keyboardIsHidden;

- (id)init {
    if ((self = [super init])) {
		self.frame = CGRectMake(0, -20, 1000, 10);
		
		_keyboardSize = CGSizeMake(0, 0);
		_keyboardIsHidden = true;
		
		{ // dummyTextField
			_dummyTextField = [[UITextField alloc] initWithFrame:CGRectZero];
			_dummyTextField.delegate = self;
			_dummyTextField.frame = self.frame;
			_dummyTextField.keyboardType = UIKeyboardTypeASCIICapable;
			[self addSubview: _dummyTextField];
			[_dummyTextField release];
		}
		
		[[NSNotificationCenter defaultCenter]addObserver:self
												selector:@selector(keyboardWillHide:)
													name:UIKeyboardWillHideNotification object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(keyboardWasShown:)
													 name:UIKeyboardDidShowNotification object:nil];
		
	}
	return self;
}


-(void) dealloc
{
	[super dealloc];
}


-(void) showKeyboard
{
	[_dummyTextField setText:@"X"];
	[_dummyTextField becomeFirstResponder];
}


-(void) hideKeyboard
{
	[_dummyTextField resignFirstResponder];
}



- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
														replacementString:(NSString *)string
{
	char inputChar;
	
	if (string.length == 1) {
		inputChar = [string characterAtIndex:0];
	}
	else if(range.length == 1){ // backspace
		inputChar = '\b';
	}
	else{
	}
	
	[_delegate keyboardViewPushed:inputChar];
	
	return NO;
}

- (void)keyboardWasShown:(NSNotification*)aNotification {
	_keyboardIsHidden = false;
	
	{ // Get the size of the keyboard.
		NSDictionary* info = [aNotification userInfo];
		NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
		_keyboardSize = [aValue CGRectValue].size;
	}

	[_delegate keyboardViewKeyboardWasShown];
} 

- (void)keyboardWillHide:(NSNotification*)aNotification { 
	_keyboardIsHidden = true;
	_keyboardSize = CGSizeMake(0, 0);
	[_delegate keyboardViewKeyboardWillHide];
} 


@end
